$(function () {
    PL.grid("gridlist", {
        colModel: [
            {header: '用户ID', name: 'userid', align: 'center', width: 150  },
            {header: '用户名', name: 'username', align: 'center', width: 200  },
            {header: '所属角色', name: 'rolename', align: 'center', width: 200  },
            {header: '注册日期', name: 'registerDate', align: 'center', width: 200  },
            {header: '状态', name: 'status', width: 50, align: 'center',
                renderer: function (colValue, rowData, rowIndex) {
                    if (colValue) {
                        return '<span style="color:green;">正常</span>';
                    } else {
                        return '<span style="color:red;">停用</span>';
                    }
                    return colValue;
                }
            },
            {header: '操作', name: 'operation', width: 200,
                renderer: function (colValue, rowData, rowIndex) {
                    var status = rowData.status;
                    var id = rowData.id;
                    var div = "<div>";
                    if (status) {
                        div = div + "<span><button type='button' class='btn btn-mini btn-inverse' onclick=Rstop('" + id + "')>停用</button></span>&nbsp;&nbsp;";
                    } else {
                        div = div + "<span><button type='button' class='btn btn-mini btn-success' onclick=Rstart('" + id + "')>启用</button></span>&nbsp;&nbsp;";
                    }
                    div = div + "<span><button type='button' class='btn btn-mini' onclick=Rupdate('" + id + "')>修改</button></span>&nbsp;&nbsp;";
                    div = div + "<span><button type='button' class='btn btn-mini btn-danger' onclick=Rdelete('" + id + "')>删除</button></span>";
                    div = div + "</div>";
                    return div;
                }}
        ],
        title: '用户列表'
    });
    search();


    $("#recordForm").validate({
        onkeyup: true,
        rules: {
            userid: "required",
            username: "required",
            roleid: "required",
            password: "required"
        },
        messages :{
            userid: "用户ID必须输入",
            username: "用户名必须输入",
            roleid: "角色必须选择",
            password: "密码必须输入"
        },
        errorPlacement: function (error, element) {
            if (error.html()) {
                $(element).parents().map(function () {
                    var attentionElement = $(this).children().eq(1);
                    if (this.tagName.toLowerCase() == 'td') {
                        attentionElement.html(error);
                        attentionElement.css('display', 'none'); //覆盖默认显示方法，先隐藏消息，等鼠标移动上去再显示
                        //attentionElement.prev().addClass("error-border");
                        attentionElement.prev().children("input").addClass("x-form-invalid");
                        if (attentionElement.prev().children().length <= 0)
                            attentionElement.prev().addClass("x-form-invalid");
                    }
                });
            }
        },
        //控制错误显示隐藏的方法，当自定义了显示方式之后一定要在这里做处理。
        showErrors: function (errorMap, errorList) {
            if (errorList && errorList.length > 0) {
                $.each(errorList, function (index, obj) {
                    var msg = this.message;
                    $(obj.element).parents().map(function () {
                        if (this.tagName.toLowerCase() == 'td') {
                            var attentionElement = $(this).children().eq(1);
                            attentionElement.show();
                            attentionElement.html(msg);
                        }
                    });
                });
            } else {
                $(this.currentElements).parents().map(function () {
                    if (this.tagName.toLowerCase() == 'td') {
                        $(this).children().eq(1).hide();
                        //$(this).children().eq(0).removeClass("error-border");
                    } else {
                        $(this).removeClass("error-border");
                    }
                    $(this).children().eq(0).removeClass("x-form-invalid");
                });
            }
            this.defaultShowErrors();
        }
    });

    //给输入框绑定鼠标经过事件，鼠标移动过去才显示校验信息
    $('.errorMsg').prev()
        .bind('mouseover',function (e) {
            //要有错误才显示
            if ($(this).next().html().length > 0 && $(this).next().find("label").html().length > 0) {
                $(this).next().css('display', 'inline').css({'top': e.pageY + 10, 'left': e.pageX + 5});
                if ($(this).next().find("label").css('display') == 'none') {
                    $(this).next().hide();
                }
            }
        }).bind('mouseout', function () {
            $(this).next().css('display', 'none');
        });

    $("#recordDialog").omDialog({
        autoOpen: false,
        modal: true,
        width: 600,
        height: 400
    });

    /*====================================*/
    $("#btnSearch").click(function () {
        search();
    });

    $("#search").bind('keydown', function (e) {
        var key = e.which;
        if (key == 13) {
            search();
        }
    });

    $("#btnAdd").click(function () {
//        $("#recordDialog").find(".uyunsky_base").each(function () {
//            $(this).val("");
//        })
        $("#recordForm").find("input").each(function(){
            $(this).removeClass("x-form-invalid");
        })

        $("#recordForm")[0].reset();
        $("#recordDialog").omDialog('open');
    });

    $("#btnSave").click(function () {
        var data = PL.getData("recordForm");
        var id = data.id;
        if (PL.isEmpty(id)) {
            data.optype = "ADD";
        } else {
            data.optype = "UPD";
        }

        //校验
        if (!$("#recordForm").valid()) {
            return false;
        }

        PL.doService("PLUserService", data, {
            success: function () {
                $("#recordDialog").omDialog('close');
                $("#gridlist").omGrid("reload");
            }
        });
    });

    function search() {
        var data = {
            optype: 'SEARCH',
            parameter: $("#search").val()
        };
        $("#gridlist").omGrid('load', 'PLUserService', data);
    }
});

function Rstop(id) {
    PL.doService("PLUserService", {
        optype: 'STOP',
        id: id
    }, {
        success: function () {
            $("#gridlist").omGrid('reload');
        }
    });
}

function Rstart(id) {
    PL.doService("PLUserService", {
        optype: 'START',
        id: id
    }, {
        success: function () {
            $("#gridlist").omGrid('reload');
        }
    });
}

function Rupdate(id) {
    PL.doService("PLUserService", {
        optype: 'GET',
        id: id
    }, {
        success: function (data) {
            //TODO 清除校验的样式;包含border 和errmsg
            $("#recordForm input").each(function(){
                $(this).removeClass("x-form-invalid");
            })
            $("#recordForm .errorMsg").each(function(){
                $(this).text("");
            })
            $("#recordDialog").omDialog('open');
        }
    });
}

function Rdelete(id) {
    var rowDatas = $("#gridlist").omGrid('getData').rows;
    for (var i = 0; i < rowDatas.length; i++) {
        var r = rowDatas[i];
        var userid = r.userid;
        if (id == r.id) {
            if (confirm("确认删除[" + userid + "]")) {
                PL.doService("PLUserService", {
                    optype: 'DEL',
                    id: id
                }, {
                    success: function () {
                        $("#gridlist").omGrid('reload');
                    }
                });
            }
        }
        return;
    }
}